package middleware

import (
	"bytes"
	"encoding/json"
	"gin-admin/common/dto/response"
	"gin-admin/service/dto/request"
	"gin-admin/utils"
	"io"
	"strings"

	"github.com/gin-gonic/gin"
)

func AuthorizationMiddleware() gin.HandlerFunc {
	return func(ctx *gin.Context) {
		if ctx.Request.URL.Path == "/api/v1/user/create" && ctx.Request.Method == "POST" {
			bodyBytes, err := io.ReadAll(ctx.Request.Body)
			if err != nil {
				response.Failed(ctx)
				ctx.Abort()
				return
			}

			ctx.Request.Body = io.NopCloser(bytes.NewBuffer(bodyBytes))
			var requestData request.CreateUserRequest

			if err := json.Unmarshal(bodyBytes, &requestData); err == nil && requestData.Account == "admin" {
				ctx.Next()
				return
			}
		}
		authHeader := ctx.Request.Header.Get("Authorization")
		if authHeader == "" || !strings.HasPrefix(authHeader, "Bearer ") {
			response.FailedWithCode(ctx, response.UnauthorizedCode)
			ctx.Abort()
			return
		}
		token := strings.TrimPrefix(authHeader, "Bearer ")
		claims, err := utils.ParseToken(token)
		if err != nil {
			response.FailedWithCode(ctx, response.UnauthorizedCode)
			ctx.Abort()
			return
		}
		ctx.Set("user_id", claims.UserID)
		ctx.Set("is_admin", claims.IsAdmin)
		ctx.Next()
	}
}
